package net.devkit.core.mail;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * 使用Spring进行封装的Javamail,抽象的邮件服务,默认使用Velocity封装了系统必备的邮件
 * <ul>
 * 	<li>发送当天的提醒邮件</li>
 * </ul>
 * 
 */
@Service
public class MailService {

	public static final String MAIL_REMIND = "REMIND";

	@Resource
	JavaMailSender javaMailSender;// 直接使用Javamail

	@Resource
	VelocityMimeMessagePreparator mailPreparator;

	private Logger logger = Logger.getLogger(this.getClass().getName());

	/**
	 * 发送使用了Velocity做模板的复杂邮件
	 * @param m 要发送的邮件上下文
	 */
	public void sendRemindMail(MailEntity m) {

		Map<String, Object> dataContext = new HashMap<String, Object>();
		dataContext.putAll(m.getData());
		dataContext.put("target", m.getTarget());

		mailPreparator.setMailId(MAIL_REMIND);
		mailPreparator.setDataContext(dataContext);
		mailPreparator.setTo(m.getTarget());
		javaMailSender.send(mailPreparator);
		logger.info(String.format("向%s发送了一封提醒邮件,标题为%s", m.getTarget(), mailPreparator.getTo()));
	}
	
	/**
	 * 发送使用了Velocity做模板的复杂邮件
	 * @param m 要发送的邮件上下文
	 * @param mailRemindKey 模板邮件缓存的Key
	 */
	public void sendRemindMail(MailEntity m,String mailRemindKey){
		Map<String, Object> dataContext = new HashMap<String, Object>();
		dataContext.putAll(m.getData());
		dataContext.put("target", m.getTarget());

		mailPreparator.setMailId(mailRemindKey);
		mailPreparator.setDataContext(dataContext);
		mailPreparator.setTo(m.getTarget());

		javaMailSender.send(mailPreparator);
		logger.info(String.format("向%s发送了一封提醒邮件,标题为%s", m.getTarget(), mailPreparator.getTo()));
	}

	public void sendSimpleMailMessage(String to, String subject, String from, String content) {

		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo(to);
		message.setSubject(subject);
		message.setFrom(from);
		message.setText(content);

		javaMailSender.send(message);

		logger.info("发送了一封邮件<" + to + ">,主题为<" + subject + ">");

	}

}
